package com.jn.algorithm.day022.question67;

/**
 * @author 江南大学1033190417
 * @date 2022/5/13 23:47
 */
public class Solution {
    public String addBinary(String a, String b) {
        int la = a.length();
        int lb = b.length();
        int n = 1;
        int l = Math.min(la, lb);
        int carry = 0;
        StringBuilder res = new StringBuilder();
        while (n <= l) {
            int sum = a.charAt(la - n) - '0' + b.charAt(lb - n) - '0' + carry;
            res.append(sum % 2);
            carry = sum / 2;
            n++;
        }
        if (la == l) {//如果b更长
            while (l < lb) {
                int sum = b.charAt(lb - l - 1) - '0' + carry;
                res.append(sum % 2);
                carry = sum / 2;
                l++;
            }
        }
        if (lb == l) {
            while (l < la) {
                int sum = a.charAt(la - l - 1) - '0' + carry;
                res.append(sum % 2);
                carry = sum / 2;
                l++;
            }
        }
        res.append(carry == 1 ? 1 : "");
        return res.reverse().toString();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.addBinary("110", "1"));
    }
}
